package app.biz.service;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Record;
import io.seata.rm.tcc.api.BusinessActionContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 构造通用存取结果集：使用actionName、XID可以定位一个唯一结果
 */
public class ResultHolder {
    private static Map<String, Map> perContxt = Maps.newHashMap();
    /**
    * 结果集结构：
     * name1 -> results1:{
    *              xid1 -> result1,
    *              xid2 -> result2
    *           }
    *  name2 -> results2...
    */
    public static void  setResult(BusinessActionContext actionContext, Record result){
        Map<String, Record> recordResults = perContxt.get(actionContext.getActionName());
        if(recordResults!=null){
            recordResults.put(actionContext.getXid(),result);
        }
        else {
            recordResults = new ConcurrentHashMap<>();
            recordResults.put(actionContext.getXid(),result);
            perContxt.put(actionContext.getActionName(), recordResults);
        }
    }

    public static Record getResult(BusinessActionContext actionContext){
        Map<String, Record> recordResults  = perContxt.get(actionContext.getActionName());
        // 存在TCC事务未提交即进行回滚的可能，因此recordResults可以为NULL
        if(recordResults == null){
            return null;
        }
        return recordResults.get(actionContext.getXid());
    }
}
